package com.xxgg.system.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xxgg.common.exception.ApiException;
import com.xxgg.common.exception.Asserts;
import com.xxgg.system.mapper.UserRoleMapper;
import com.xxgg.system.model.po.User;
import com.xxgg.system.mapper.UserMapper;
import com.xxgg.system.model.po.UserRole;
import com.xxgg.system.model.vo.UserRoleVo;
import com.xxgg.system.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 先谢郭嘉
 * @since 2023-01-31 04:33:30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    UserMapper userMapper;

    @Resource
    UserRoleMapper userRoleMapper;

    @Override
    public UserRoleVo getUserRole(String userId) {
        return userMapper.getUserRole(userId);
    }

    @Override
    public boolean isUserName(String userName) {
        long count = userMapper.selectCount(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, userName));
        return count > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addUser(User user) throws ApiException {
        Asserts.isTrue(isUserName(user.getUserName()), "用户名已存在！");

        user.setUserId(IdUtil.simpleUUID());
        user.setPassword(SaSecureUtil.md5BySalt(user.getUserName(), user.getPassword()));

        // 新增用户
        long count = userMapper.insert(user);
        Asserts.isFalse(count > 0, "新增用户失败！");

        // 关联用户和角色
        count = userRoleMapper.insert(UserRole.builder()
                .roleId(user.getRoleId())
                .userId(user.getUserId())
                .build());
        Asserts.isFalse(count > 0, "新增用户关联关系失败！");
        return count > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateUser(User user) throws ApiException {
        Asserts.isFalse(StrUtil.isNotBlank(user.getUserId()), "用户id为空！");
        // 根据用户id查询用户信息（版本号）
        User userV = userMapper.selectById(user.getUserId());

        // 编辑用户（版本号需一致）
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getUserId, user.getUserId())
                .eq(User::getVersion, userV.getVersion());
        user.setVersion(user.getVersion() + 1);
        long count = userMapper.update(user, wrapper);
        Asserts.isFalse(count > 0, "编辑用户失败！");

        // 若用户角色改变，则删除用户角色关联关系，并新增关联
        LambdaUpdateWrapper<UserRole> userRoleWrapper = new LambdaUpdateWrapper<UserRole>()
                .eq(UserRole::getUserId, user.getUserId());
        UserRole userRole = userRoleMapper.selectOne(userRoleWrapper);
        // 判断用户角色是否改变
        if(!userRole.getRoleId().equals(user.getRoleId())){
            // 删除用户角色关联关系
            count = userRoleMapper.delete(userRoleWrapper);
            Asserts.isFalse(count > 0, "修改用户角色失败！");
            // 新增用户角色关联关系
            count = userRoleMapper.insert(UserRole.builder()
                    .roleId(user.getRoleId())
                    .userId(user.getUserId())
                    .build());
            Asserts.isFalse(count > 0, "修改用户角色失败！");
        }
        return count > 0;
    }
}
